<template>
  <Page title='批改结果' @gesture='onGesture' :on-page-back='onPageBack'>
    <template #content>
      <div class='w-full h-full p-20px box-border'>
        <div class='englishWritingResult box-border flex flex-col'>
          <div class='enDemoWrap' v-if='all_data.overall_result'>
            <div class='left'>
              <div class='breadExpand'>
                <div style='margin-top: 20px;' v-for='(e,key) in Object.keys(breadList)' :key='key'>
                  <BreadExpandTab
                    :index='key'
                    :options='INFO_MAP'
                    :type='e'
                    :data='breadList[e]'
                    @handleBreadItemClick='handleBreadItemClick'
                  />
                </div>
              </div>
              <div class='content'>
                <div class='articleParagraph' v-for='(paragraph,key) in activeComposition' :key='key'>
                  <template v-for='(value,index) in paragraph'>
                    <template v-if='value.isBorder'>
                      <el-popover
                        :key='index'
                        placement='top-start'
                        title=''
                        trigger='click'
                        :content='handlePopContent(value)'
                        @show='handleTextHover(value.index)'
                      >
                        <span slot='reference'>
                          <span
                            class='textWrap'
                            :class='value.isBorder ? "borderText" : ""'
                            :style="`border-color: ${activeTab.titleColor}; background: ${activeObj.active === value.index
                                ? activeObj.highlightColor
                                : 'transparent'};`">
                            {{ value.text }}
                            <span v-if='value.isBorder' class='grade'
                                  :style='`background: ${activeTab.titleColor}`'>{{ value.index }}</span>
                          </span>
                        </span>
                      </el-popover>
                    </template>
                    <span
                      v-else
                      :key='index'
                      class='textWrap'
                      :class='value.isBorder ? "borderText" : ""'
                      :style="`border-color: ${activeTab.titleColor}; background: ${activeObj.active === value.index
                            ? activeObj.highlightColor
                            : 'transparent'};`"
                    >
                        {{ value.text }}
                        <span v-if='value.isBorder' class='grade'
                              :style='`background: ${activeTab.titleColor}`'>{{ value.index }}</span>
                      </span>
                  </template>
                </div>
              </div>
            </div>
            <div class='right'>
              <div class='score'>
                <div class=''>总分</div>
                <div class='score-val ml-10px'>{{ convertScore(overall_result.total_score,15) }}</div>
                <div class='score-info'>分</div>
              </div>
              <div class='content'>
                <div v-for='(e,i) in Object.keys(overall_result.category_score)' :key='i'>
                  <template v-if='overall_result.category_score[e].score'>
                    <p class='title'>
                      <span>{{ PROGRESS_INFO[e][0] }}:</span>
                      <span class='color-blue ml-10px'>{{ convertScore(overall_result.category_score[e].score,5) }}</span>
                      <span>分</span>
                    </p>
                    <p class='categoryContent'>{{ overall_result.category_score[e].comment }}</p>
                  </template>
                </div>
                <p class='title'>总评</p>
                <p class='categoryContent'>{{ overall_result.total_comment }}</p>
              </div>
            </div>
          </div>
          <el-empty v-else :image-size='200'></el-empty>
        </div>
      </div>
    </template>
  </Page>
</template>
<script>
import Page from '@/components/page/index.vue'
import { postEnTextCorrectionApi } from '@/api/correct-english'
import BreadExpandTab from '@/views/correct/english/components/BreadExpandTab.vue'
import {
  PROGRESS_INFO,
  INFO_MAP,
  getClauseArticle,
  getPhrasesArticle,
  getConjunctionArticle,
  getProposalData,
  getError, getProposalListData, getConjunctionList, getPhrasesList, getClauseList, mockData
} from './enCorrection'
import axios from 'axios'

export default {
  components: {
    BreadExpandTab,
    Page
  },
  data() {
    return {
      imgList: [],
      all_data: {},
      overall_result: {},
      errorWords: [],
      conjunctionList: [],
      phrasesList: [],
      suggestionWord: [],
      clauseList: [],
      INFO_MAP: INFO_MAP,
      activeObj: {},
      activeTab: {},
      popoverVisibles: []
    }
  },
  computed: {
    breadList() {
      const checkList = {
        errorWords: this.errorWords,
        conjunctionList: this.conjunctionList,
        phrasesList: this.phrasesList,
        suggestionWord: this.suggestionWord,
        clauseList: this.clauseList
      }
      let res = {}
      res = Object.keys(checkList).reduce((acc, key) => {
        if (checkList[key] !== undefined && checkList[key].length > 0) {
          acc[key] = checkList[key]
        }
        return acc
      }, {})
      return res
    },
    structureList() {
      if (Object.keys(this.all_data).length === 0) return
      const errorWordsStruct = getError(this.all_data)
      const suggestionWordStruct = getProposalData(this.all_data)
      const conjunctionListStruct = getConjunctionArticle(this.all_data)
      const phrasesListStruct = getPhrasesArticle(this.all_data)
      const clauseListStruct = getClauseArticle(this.all_data)
      return {
        errorWordsStruct,
        suggestionWordStruct,
        conjunctionListStruct,
        phrasesListStruct,
        clauseListStruct
      }
    },
    activeComposition() {
      const activeType = this.activeTab.structureName || Object.keys(this.structureList)[0]
      console.log('activeType', activeType)
      console.log('this.structureList', this.structureList)
      return this.structureList[activeType]
    },
    PROGRESS_INFO() {
      return PROGRESS_INFO
    }
  },
  watch: {
    structureList: {
      handler(val) {
        const head = Object.keys(val)[0]
        const type = head?.split('Struct')[0]
        this.activeTab = {
          type,
          structureName: head,
          titleColor: INFO_MAP[type]?.titleColor
        }
      },
      immediate: true
    }
  },
  methods: {
    init() {
      if (this.imgList.length === 0) {
        this.$message.error('请先上传作文.')
        return
      }
      const loading = this.$loading({
        target: '.englishWritingResult',
        body: false,
        text: '批改中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      postEnTextCorrectionApi({ image_base64: this.imgList }).then(res => {
        let data = res.data
        if (data) {
          this.handleCorrectDataEN(data)
        } else {
          this.$message.error(res.msg)
        }
        loading.close()
      })
    },
    getDataByJson(json) {
      const loading = this.$loading({
        target: '.englishWritingResult',
        body: false,
        text: '批改中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      axios({
        method: 'get',
        url: json,
        responseType: 'json'
      }).then(res => {
        let data = res.data
        if (data) {
          this.handleCorrectDataEN(data)
        } else {
          this.$message.error(res.msg)
        }
        loading.close()
      })
    },
    handleCorrectDataEN(commentsData) {
      this.all_data = commentsData
      // 纠错数据
      this.errorWords = commentsData.gec_result
        .map((item) => {
          return item.error_info
        })
        .flat()
      // 建议数据
      this.suggestionWord = getProposalListData(commentsData)
      // 连词数据
      this.conjunctionList = getConjunctionList(commentsData)
      // 词组数据
      this.phrasesList = getPhrasesList(commentsData)
      // 从句数据
      this.clauseList = getClauseList(commentsData)
      // 总评
      this.overall_result = commentsData.overall_result

      const originTitle = commentsData.original_essay_info.title
      const originContent =
        commentsData.original_essay_info.original_paragraph_list
      return { originTitle, originContent } || {}
    },
    handleBreadItemClick(item, index, infoObj) {
      const { highlightColor, type, structureName, titleColor } = infoObj
      this.activeTab = { type, structureName, titleColor }
      this.activeObj = { ...item, active: index + 1, highlightColor, titleColor }
      console.log('activeObj', this.activeObj)
    },
    handleTextHover(index) {
      const { type } = this.activeTab
      const { highlightColor } = INFO_MAP[type]
      this.activeObj = {
        ...this.activeObj,
        highlightColor,
        active: index
      }
    },
    handlePopContent({ index }) {
      console.log(this.breadList)
      const item = this.breadList[this.activeTab.type]?.[index - 1]
      switch (this.activeTab.type) {
        case 'errorWords':
          return item?.error_description
        case 'suggestionWord':
          return `把“${item?.word}”调整为“${item?.candidates[0]}”是否更合适？`
        case 'conjunctionList':
          return `${item?.contentType} ${item?.word} ${item?.ending}`
        case 'clauseList':
          return `${item?.contentType} ${item?.content} ${item?.ending}`
        case 'phrasesList':
          return `${item?.meaning}`
        default:
          return ''
      }
    },
    convertScore(score, base = 100) {
      return Math.round(score / base * 100)
    },
    onPageBack() {
      this.$router.back()
    },
    onGesture(e) {
      console.log('onGesture', e)
    }
  },
  mounted() {
    const query = this.$route.query
    if (query.fileUrl) {
      this.getDataByJson(query.fileUrl)
    } else {
      this.imgList = this.$store.state.correctEnglish.imgList
      this.init()
    }
  }
}
</script>

<style scoped lang='scss'>
.englishWritingResult {
  font-size: 18px;
  color: #333333;
  padding: 20px;
  background: #fff;
  border-radius: 16px;
  height: 100%;
  overflow-y: auto;

  .color-blue {
    color: #51C3FF;
  }
}

.enDemoWrap {
  display: flex;
  width: 100%;
  min-height: 550px;

  .left {
    display: flex;
    flex: 1;
    background: #FFFFFF;

    .breadExpand {
      padding: 0 10px;
      overflow-y: auto;

      .breadExpandTabItem,
      .breadExpandTabWrap .breadExpandTabContent > li {
        width: 100%;
        height: 44px;
        line-height: 44px;
        box-sizing: border-box;
        margin-top: 10px;
        background: #FFFFFF;
        box-shadow: 0 2px 3px 1px rgba(0, 0, 0, 0.08);
        border-radius: 15px;
        padding: 0 10px;
        cursor: pointer;
      }
    }

    .content {
      background: #F4F7FB;
      border: 1px solid #F4F7FB;
      padding: 20px 20px;
      width: 600px;
      overflow-y: auto;
      color: #666666;
    }
  }

  .right {
    width: 320px;
    padding: 0 10px;
    overflow-y: auto;

    .score {
      display: flex;
      align-items: baseline;
      font-size: 20px;
      color: #333333;
      margin-bottom: 10px;
      font-weight: 500;

      &::before {
        content: '';
        display: inline-block;
        width: 6px;
        height: 1em;
        margin-right: 0.5em;
        background: linear-gradient(180deg, #51C3FF 0%, #31B3F7 100%);
        border-radius: 3px;
        transform: translate(0, 20%);

      }
    }

    .score-val {
      color: #30C9A1;
      font-size: 50px;
      font-weight: bolder;
    }
    .score-info{
      color: #30C9A1;
    }

    .font-50 {
      font-size: 50px;
    }

    .title {
      display: flex;
      align-items: center;
      font-size: 20px;
      font-weight: 500;
      color: #333333;
      margin-bottom: 8px;

      &::before {
        content: '';
        display: inline-block;
        width: 6px;
        height: 1em;
        margin-right: 0.5em;
        background: linear-gradient(180deg, #51C3FF 0%, #31B3F7 100%);
        border-radius: 3px;
        vertical-align: center;
      }
    }

    .content {
      .categoryContent {
        line-height: 22px;
        margin-bottom: 16px;
        color: #444444;
        font-size: 16px;
      }
    }
  }
}

.articleParagraph > span {
  line-height: 40px;
}

.textWrap {
  position: relative;
}

.borderText {
  border-bottom: 1px solid;
}

.grade {
  position: absolute;
  display: inline-block;
  width: 16px;
  height: 16px;
  left: -12px;
  top: -9px;
  font-size: 12px;
  font-weight: 500;
  vertical-align: middle;
  line-height: 16px;
  color: #fff;
  text-align: center;
  border-radius: 50%;
}

</style>
